package cn.com.customer.manager.ui.main


import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.KeyEvent
import android.widget.PopupWindow
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import cn.com.customer.manager.Constants
import cn.com.customer.manager.R
import cn.com.customer.manager.adapter.HomeFragmentAdapter
import cn.com.customer.manager.application.App
import cn.com.customer.manager.base.BaseActivity
import cn.com.customer.manager.base.HiActivityStack
import cn.com.customer.manager.http.update.XHttpUpdateHttpService
import cn.com.customer.manager.http.update.custom.XUpdateServiceParser
import cn.com.customer.manager.manager.TokenManager
import cn.com.customer.manager.ui.customer.customerList.CustomerFragment
import cn.com.customer.manager.ui.order.list.OrderFragment
import cn.com.customer.manager.ui.fragment.me.MineFragment
import cn.com.customer.manager.ui.task.list.TaskFragment
import cn.com.customer.manager.utils.phone.PhoneService
import com.xuexiang.xfloatview.permission.FloatWindowPermission
import com.xuexiang.xupdate.XUpdate
import com.xuexiang.xupdate.entity.UpdateError
import com.xuexiang.xupdate.utils.UpdateUtils
import com.xuexiang.xutil.net.JsonUtil
import com.xuexiang.xutil.tip.ToastUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_main_footer.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.MutableMap
import kotlin.collections.set


class MainActivity : BaseActivity() {

    private lateinit var adapter: HomeFragmentAdapter
    private lateinit var taskFragment: TaskFragment
    private lateinit var orderFragment: OrderFragment
    private lateinit var customerFragment: CustomerFragment
    private lateinit var mineFragment: MineFragment
    private lateinit var phoneService: PhoneService
    private var phoneIntent: Intent? = null
    private var mPopWindow: PopupWindow? = null
    private var id: String = ""
    private val listpages: ArrayList<Fragment> = ArrayList()
    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView(savedInstanceState: Bundle?) {
        FloatWindowPermission.getInstance().applyFloatWindowPermission(this)
        registerPhoneService()
        initfragmentdata()
        initUpdate()
        XUpdate.newBuild(this)
                .updateUrl(Constants.BASE_URL)
                .updateParser(XUpdateServiceParser()) //设置自定义的版本更新解析器
                .update();
    }
    private fun initUpdate() {
        val map: MutableMap<String, String> = HashMap()
        map["versionNum"] = UpdateUtils.getVersionName(this)
        map["versionCode"] = UpdateUtils.getVersionCode(this).toString()
        XUpdate.get()
                .debug(true)
                .isWifiOnly(false) //默认设置只在wifi下检查版本更新
                .isGet(false) //默认设置使用get请求检查版本
                .isAutoMode(false) //默认设置非自动模式，可根据具体使用配置
                .param("token", TokenManager.getInstance().token) //设置默认公共请求参数
                .param("data", JsonUtil.toJson(map))
                .setOnUpdateFailureListener { error ->
                    //设置版本更新出错的监听
                    error.printStackTrace()
                    if (error.code != UpdateError.ERROR.CHECK_NO_NEW_VERSION) { //对不同错误进行处理
                        ToastUtils.toast(error.toString())
                    }
                }
                .supportSilentInstall(false) //设置是否支持静默安装，默认是true
                .setIUpdateHttpService(XHttpUpdateHttpService(Constants.BASE_URL)) //这个必须设置！实现网络请求功能。
                .init(App.getContext() as Application?) //这个必须初始化
    }

    private fun registerPhoneService() {
        phoneIntent = Intent(this, PhoneService::class.java)
        this.startService(phoneIntent)
    }

    override fun onResume() {
        super.onResume()

    }

    override fun onPause() {
        super.onPause()

    }

    override fun onDestroy() {
        super.onDestroy()
        this.stopService(phoneIntent)
    }

    private fun initfragmentdata() {
        customerFragment = CustomerFragment()
        taskFragment = TaskFragment()
        orderFragment = OrderFragment()
        mineFragment = MineFragment()
        listpages.add(customerFragment)
        listpages.add(taskFragment)
        listpages.add(orderFragment)
        listpages.add(mineFragment)
        // 添加显示第一个fragment
        adapter = HomeFragmentAdapter(supportFragmentManager, 0, listpages)
        container.adapter = adapter
        container.offscreenPageLimit = 4
        container.currentItem = 1
        group.check(R.id.foot_bar_2)
        group.setOnCheckedChangeListener { _, checkedId ->
            var position =2
            when (checkedId) {
                R.id.foot_bar_1 -> position = 1
                R.id.foot_bar_2 -> position = 2
                R.id.foot_bar_3 -> position = 3
                R.id.foot_bar_4 -> position = 4
            }
            setRadio(position)
        }
        container.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
            override fun onPageSelected(position: Int) {
                setRadio(position+1)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }


    fun setRadio(position: Int) {
        when (position) {
            1 -> {
                foot_bar_1.isChecked = true
                container.currentItem = 0

            }
            2 -> {
                foot_bar_2.isChecked = true
                container.currentItem = 1
            }

            3 -> {
                foot_bar_3.isChecked = true
                container.currentItem = 2
            }
            4 -> {
                foot_bar_4.isChecked = true
                container.currentItem = 3
            }
        }
    }

    override fun onAttachFragment(fragment: Fragment) {
        super.onAttachFragment(fragment)
        if ( fragment is CustomerFragment) {
            customerFragment = CustomerFragment()
        } else if ( fragment is OrderFragment) {
            orderFragment = OrderFragment()
        } else if ( fragment is TaskFragment) {
            taskFragment = TaskFragment()
        } else if ( fragment is MineFragment) {
            mineFragment = MineFragment()
        }
    }


    /**
     * 是否退出
     */
    private var mIsExit = false

    /**
     * 双击返回键退出
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mIsExit) {
                HiActivityStack.getInstance().appExit()
            } else {
                ToastUtils.toast("再点一次退出")
                mIsExit = true
                Handler().postDelayed({
                    mIsExit = false
                }, 2000)
            }

            return true
        }
        return super.onKeyDown(keyCode, event)
    }

}
